import {Injectable} from '@angular/core';
import {Http, URLSearchParams, Response, Headers} from '@angular/http';
import {Router} from '@angular/router';
@Injectable()

export class HttpService {
  headers;
  constructor (private http: Http, private router: Router) {}
  request(url: string, method: 'Get'|'Post', data = {}) {
    const t = localStorage.getItem(('login'));
    if (t) {
      const tu = JSON.parse(t);
      this.headers = new Headers({'x-access-token': tu.token});
    }
    if (method === 'Get') {
      const params = new URLSearchParams();
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          params.set(key, data[key]);
        }
      }
      console.log('token', this.headers);
      return this.http.get(url, {search: params, headers: this.headers})
        .map(
          (response: Response) => {
            const res = response.json();
            if (res.code !== 1) {
              this.router.navigate(['/login']);
            }
            return res;
          }
        );
    } else if (method === 'Post') {
      return this.http.post(url, data, {headers: this.headers})
        .map(
          (response: Response) => {
            const res = response.json();
            if (res.code !== 1) {
              this.router.navigate(['/login']);
            }
            return res;
          }
        );
    }
  }
}
